<template>
   <div>
      <el-breadcrumb separator="/">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item><a href="javascript:;">会员管理</a></el-breadcrumb-item>
         <el-breadcrumb-item>会员列表</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="hengxian"></div>

      <el-row>
         <el-col :span="15">
            <el-button type="primary" size="mini" @click="dialogTableCreate = true">
               <i class="el-icon-plus"></i><span>新增</span>
            </el-button>
         </el-col>
         <el-col :span="5">
            <div>
               <el-input placeholder="请输入内容" v-model="keyword" class="input-with-select" size="mini">
                  <el-select v-model="cate" slot="prepend" placeholder="请选择">
                     <el-option label="ID" value="id"></el-option>
                     <el-option label="名称" value="name"></el-option>
                     <el-option label="电话" value="phone"></el-option>
                     <el-option label="邮箱" value="email"></el-option>
                  </el-select>
                  <el-button slot="append" @click="handleSearch" icon="el-icon-search"></el-button>
               </el-input>
            </div>
         </el-col>
      </el-row>

      <el-table :data="users" style="width: 100%;margin-bottom: 20px;" row-key="id" border
                default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
         <el-table-column label="ID" prop="id" width="90"></el-table-column>
         <el-table-column label="头像" prop="headimgurl">
            <template slot-scope="scope">
               <el-avatar size="small" v-if="scope.row.headimgurl" :src="scope.row.headimgurl"></el-avatar>
            </template>
         </el-table-column>
         <el-table-column label="OPENID" prop="openid"></el-table-column>
         <el-table-column label="姓名" prop="name"></el-table-column>
         <el-table-column label="电话" prop="phone"></el-table-column>
         <el-table-column label="邮箱" prop="email"></el-table-column>
         <el-table-column label="性别" prop="sex" width="55">
            <template slot-scope="scope">
               <i v-if="scope.row.sex == 1" class="el-icon-user man"></i>
               <i v-else class="el-icon-user famale"></i>
            </template>
         </el-table-column>
         <el-table-column label="省份" prop="province"></el-table-column>
         <el-table-column label="市区" prop="city"></el-table-column>
         <el-table-column label="订单详情" prop="">
            <template slot-scope="scope">
               <router-link :to="{name:'orders',params: { user_id: scope.row.id }}">
                  <el-button v-if="scope.row.orders != ''" type="success" size="mini">查看</el-button>
               </router-link>
            </template>
         </el-table-column>
         <el-table-column label="操作">
            <template slot-scope="scope">
               <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                  <i class="el-icon-edit" @click="handleEdit(scope.$index,scope.row)"></i>
               </el-tooltip>
               <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <i class="el-icon-delete" @click="handleDelete(scope.$index,scope.row)"></i>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>

      <!--分页-->
      <div class="page">
         <span class="total">共 {{page.total}} 条数据</span>
         <el-pagination background :total="page.total" :page-size="page.size" @current-change="handleCurrentChange"
                        :current-page.sync="page.currentPage" layout="prev, pager, next">
         </el-pagination>
      </div>

      <!--新增会员模态框-->
      <el-dialog title="新增会员" :visible.sync="dialogTableCreate" @close='closeDialog'>
         <el-form :model="user" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="姓名" prop="name">
               <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="headimgurl">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="user.headimgurl" :src="user.headimgurl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
               <el-radio-group v-model="user.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
               <el-input v-model="user.phone" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
               <el-input type="url" v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
               <el-input type="password" v-model="user.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="password_confirmation">
               <el-input type="password" v-model="user.password_confirmation" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="user">
               <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
               <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>

      <!--编辑会员-->
      <el-dialog title="编辑会员" :visible.sync="dialogTableEdit" @close='closeDialog'>
         <el-form :model="user" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="姓名" prop="name">
               <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="headimgurl">
               <el-upload class="avatar-uploader" action="/photos" :show-file-list="false"
                          :on-success="handleAvatarSuccess"
                          :before-upload="beforeAvatarUpload">
                  <img v-if="user.headimgurl" :src="user.headimgurl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
               </el-upload>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
               <el-radio-group v-model="user.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
               <el-input v-model="user.phone" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
               <el-input type="url" v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item label="原密码" prop="oldPass">
               <el-input type="password" v-model="user.oldPass"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
               <el-input type="password" v-model="user.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="password_confirmation">
               <el-input type="password" v-model="user.password_confirmation" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="user">
               <el-button type="primary" @click="updateForm('ruleForm')" size="mini">更新</el-button>
               <el-button @click="resetForm('ruleForm')" size="mini">重置</el-button>
            </el-form-item>
         </el-form>
      </el-dialog>
   </div>
</template>

<script>
   export default {
      name: "Home",
      data() {
         const validatePass = (rule, value, callback) => {
            if (value === undefined || value === '') {
               callback(new Error('请输入密码'));
            } else {
               if (this.user.password_confirmation !== '') {
                  this.$refs.ruleForm.validateField('password_confirmation');
               }
               callback();
            }
         };
         const validatePass2 = (rule, value, callback) => {
            if (value === undefined || value === '') {
               callback(new Error('请再次输入密码'));
            } else if (value !== this.user.password) {
               callback(new Error('两次输入密码不一致!'));
            } else {
               callback();
            }
         };
         return {
            loading: false,
            keyword: '',
            cate: '',
            users: [],
            dialogTableCreate: false,
            user: {
               name: '',
               headimgurl: '',
               phone: '',
               email: '',
               sex: 1,
               password: '',
               password_confirmation: ''
            },
            rules: {
               name: [
                  {required: true, message: '请输入昵称', trigger: 'blur'},
                  {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
               ],
               phone: [
                  {required: true, message: '请输入电话', trigger: 'blur', max: 11}
               ],
               email: [
                  {required: true, message: '请输入邮箱地址', trigger: 'blur'},
                  {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
               ],
               oldPass: [
                  {required: true, trigger: 'blur'}
               ],
               password: [
                  {validator: validatePass, required: true, trigger: 'blur'}
               ],
               password_confirmation: [
                  {validator: validatePass2, required: true, trigger: 'blur'}
               ],
            },
            page: {
               total: 0,  //总数
               size: 0,  //每页显示数
               currentPage: 1,
            },
            dialogTableEdit: false,
         }
      },
      created() {
         this.init();
      },
      methods: {
         //搜索
         handleSearch() {
            this.init();
         },
         //分页--获取当前页
         handleCurrentChange(val) {
            this.page.currentPage = val;
            this.init();
         },
         //首页
         init() {
            this.loading = true;
            axios.get(`/admin/shop/users?page=${this.page.currentPage}&cate=${this.cate}&keyword=${this.keyword}`)
               .then((res) => {
                  // console.log(res.data);
                  this.users = res.data.data;
                  this.page.total = res.data.total;
                  this.page.size = res.data.per_page;
                  this.loading = false;
               })
         },
         //图片上传
         handleAvatarSuccess(res, file) {
            this.user.headimgurl = res.msg;
         },
         beforeAvatarUpload(file) {
            // const isJPG = file.type === 'image/jpeg';
            const img = ['image/jpeg', 'image/png', 'image/gif'];
            const isJPG = img.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
               this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
            }
            if (!isLt2M) {
               this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
         },
         //关闭模态框,先清空验证再清除表单
         closeDialog() {
            this.$refs.ruleForm.clearValidate();
            this.$refs.ruleForm.resetFields();
            this.user = {};
         },
         //新增
         submitForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  // console.log(this.user);
                  axios.post(`/admin/shop/users`, this.user)
                     .then((res) => {
                        if (res.data.status == 1) {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'success'
                           });
                           this.dialogTableCreate = false;
                           this.init();
                           this.$refs[formName].resetFields();  //重置表单
                        } else {
                           this.$message.error(res.data.msg);
                        }
                     })
               } else {
                  console.log('error submit!!');
                  return false;
               }
            });
         },
         resetForm(formName) {
            this.$refs[formName].resetFields();
         },
         //编辑模态框
         handleEdit(index, row) {
            axios.get(`/admin/shop/users/${row.id}`)
               .then((res) => {
                  this.dialogTableEdit = true;
                  this.user = res.data;
               })
         },
         //更新
         updateForm(formName) {
            this.$refs[formName].validate((valid) => {
               if (valid) {
                  axios.put(`/admin/shop/users/${this.user.id}`, this.user)
                     .then((res) => {
                        if (res.data.status == 1) {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'success'
                           });
                           this.dialogTableEdit = false;
                           this.init();
                        } else {
                           this.$message({
                              showClose: true,
                              message: res.data.msg,
                              type: 'error'
                           });
                        }
                     })
               } else {
                  console.log('error submit!!');
                  return false;
               }
            });
         },
         //删除
         handleDelete(index, row) {
            this.$confirm('此操作将永久删除该会员, 是否继续?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning',
               center: true
            }).then(() => {
               axios.delete(`/admin/shop/users/${row.id}`)
                  .then((res) => {
                     // console.log(res);
                     if (res.data.status == 1) {
                        this.users.splice(index, 1);
                        this.$message({
                           type: 'success',
                           message: res.data.msg,
                        });
                        this.init();
                     } else {
                        this.$message.error(res.data.msg);
                     }
                  });
            }).catch(() => {
               this.$message({
                  type: 'info',
                  message: '已取消删除'
               });
            });
         },
      }
   }
</script>

<style>
   .man {
      color: green;
   }

   .famale {
      color: red;
   }

   .user {
      margin-top: 35px;
   }

</style>